/** DefaultPanel */
package client.ui.panel;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URL;
import java.util.List;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

import org.json.JSONObject;

import client.ClientManager;
import client.EventBus;
import client.events.PatientEdit;
import client.events.PatientSearch;
import client.events.ViewAppointments;
import client.events.ViewHistory;
import client.events.ViewHome;
import client.events.ViewInvoice;
import client.io.ClientIO;
import client.service.AppointmentService;
import client.service.DoctorService;
import client.service.PatientService;
import client.service.UserService;
import domain.action.Action;
import domain.patient.Patient;
import domain.permissions.Permission;
import domain.session.Request;
import domain.session.Response;
import domain.user.User;

/**
 * Panel containing the header and sidebar for other panels
 * 
 * @author jessienewman
 * @version $Revision: 1.0 $
 */
public class DefaultPanel extends JPanel {
	/**
	 * Field title.
	 */
	protected JLabel title;

	/**
	 * Field buttonBar.
	 */
	//protected JPanel buttonBar;
	public JPanel buttonBar;

	/**
	 * Field sideBar.
	 */
	protected JPanel sideBar;

	/**
	 * Field search.
	 */
	protected JTextField search;

	/** Field historyButton. */
	/** Field appointmentButton. */
	/** Field accountButton. */
	/** Field userButton. */
	/** Field invoiceButton. */
	/** Field homeButton. */
	/** Field searchGo. */
	protected JButton searchGo, homeButton, invoiceButton, userButton,
			accountButton, appointmentButton, historyButton;

	/**
	 * Field userId.
	 */
	private Integer userId;

	/**
	 * Field defaultRows.
	 */
	private static final Integer DEFAULTROWS = 4;
	private URL hUrl = getClass().getResource("house_go.png");
	public ImageIcon goHome=new ImageIcon(hUrl);
	
	private URL addUrl = getClass().getResource("add.png");
	public ImageIcon addP=new ImageIcon(addUrl);
	
	private URL moneyUrl = getClass().getResource("add.png");
	public ImageIcon inMon=new ImageIcon(moneyUrl);
	
	private URL histUrl = getClass().getResource("calendar_edit.png");
	public ImageIcon ce=new ImageIcon(histUrl);
	
	private URL heartUrl = getClass().getResource("heart.png");
	public ImageIcon heart=new ImageIcon(heartUrl);
	
	private URL accountUrl = getClass().getResource("folder_key.png");
	public ImageIcon acc=new ImageIcon(accountUrl);
	
	private URL searchUrl = getClass().getResource("find.png");
	public ImageIcon seek=new ImageIcon(searchUrl);

	/** creates a panel to serve as the header and sidebar for other panels */
	public DefaultPanel() {
		setLayout(new BorderLayout());
		setBackground(Color.WHITE);

		buttonBar = new JPanel();

		homeButton = new JButton(" Home ",goHome);
		homeButton.setBorder(BorderFactory.createRaisedBevelBorder());
		homeButton.setForeground(Color.WHITE);
		homeButton.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				EventBus.BUS.fireEvent(new ViewHome(null));
			}
		});

		userButton = new JButton(" Add User ",addP);
		userButton.setBorder(BorderFactory.createRaisedBevelBorder());
		userButton.setForeground(Color.WHITE);
		userButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent event) {
				final JSONObject patientJson = new JSONObject();
				patientJson.put("patientId", userId);
				ClientIO.sendRequest(new Request(Action.GET_PATIENT,
						patientJson));

				final Response response = ClientIO.getResponse();

				if (response.isSuccessful()) {
					final JSONObject responseJson = response.getJSON();
					final Patient filledPatient = new Patient(responseJson);
					EventBus.BUS.fireEvent(new PatientEdit(filledPatient));
				}
				EventBus.BUS.fireEvent(new PatientEdit(null));
			}
		});

		invoiceButton = new JButton(" View Invoice ",inMon);
		invoiceButton.setBorder(BorderFactory.createRaisedBevelBorder());
		invoiceButton.setForeground(Color.WHITE);
		invoiceButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				EventBus.BUS.fireEvent(new ViewInvoice(null));
			}
		});

		historyButton = new JButton(" Health History ",ce);
		historyButton.setBorder(BorderFactory.createRaisedBevelBorder());
		historyButton.setForeground(Color.WHITE);

		appointmentButton = new JButton(" Appointments ",heart);
		appointmentButton.setBorder(BorderFactory.createRaisedBevelBorder());
		appointmentButton.setForeground(Color.WHITE);

		accountButton = new JButton("Account",acc);
		accountButton.setBorder(BorderFactory.createRaisedBevelBorder());
		accountButton.setForeground(Color.WHITE);

		// Search Box
		search = new JTextField();
		searchGo = new JButton("Search",seek);

		final URL titleUrl = getClass().getResource("title.jpg");
		final ImageIcon titleImage = new ImageIcon(titleUrl);
		title = new JLabel(titleImage);
		//this.add(title, BorderLayout.NORTH);

		sideBar = new JPanel();
		sideBar.add(buttonBar);
		final JPanel fillerPanel = new JPanel();
		fillerPanel.setBackground(Color.WHITE);
		sideBar.add(fillerPanel);
		sideBar.setBackground(Color.WHITE);
		this.add(sideBar, BorderLayout.WEST);
	}

	/**
	 * returns the userId the panel is using to determine what is viewable
	 * 
	 * @return userId the panel is using to determine what is visible
	 */
	public Integer getCurrentUserId() {
		return userId;
	}
	public JPanel getButton(){
		return buttonBar;
	}

	/**
	 * updates the user of the panel by setting the userId of the SESSION
	 * 
	 * @param userId
	 *            userid to set SESSION's userId to
	 */
	public void updateUser(final Integer userId) {
		ClientManager.SESSION.setUserId(userId);

		this.userId = userId;
		int rows = DEFAULTROWS;
		if (ClientManager.SESSION.hasPermission(Permission.EDIT_PATIENT)) {
			rows++;
		}
		if (ClientManager.SESSION.hasPermission(Permission.INVOICE)) {
			rows++;
		}
		if (ClientManager.SESSION.hasPermission(Permission.PATIENT) || ClientManager.SESSION.hasPermission(Permission.DOCTOR)) {
			rows++;
		}
		if (ClientManager.SESSION.hasPermission(Permission.PATIENT)) {
			rows++;
		}

		buttonBar.setLayout(new GridLayout(rows, 1));
		buttonBar.setBackground(new Color(0, 0, 80)); // blue //
														// $codepro.audit.disable
														// numericLiterals
		// final GridLayout b = new GridLayout();

		historyButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				EventBus.BUS.fireEvent(new ViewHistory(ClientManager.SESSION
						.getUserId()));
			}
		});

		buttonBar.add(homeButton);

		if (ClientManager.SESSION.hasPermission(Permission.PATIENT)) {
			buttonBar.add(appointmentButton);
			appointmentButton.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent event) {
					EventBus.BUS.fireEvent(new ViewAppointments(
							AppointmentService.getPatientAppointments(userId),
							PatientService.getPatient(userId)));
				}
			});
			buttonBar.add(historyButton);
		} else if (ClientManager.SESSION.hasPermission(Permission.DOCTOR)) {
			buttonBar.add(appointmentButton);
			appointmentButton.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent event) {
					EventBus.BUS.fireEvent(new ViewAppointments(
							AppointmentService.getDoctorAppointments(userId),
							DoctorService.getDoctor(userId)));
				}
			});
		}

		if (ClientManager.SESSION.hasPermission(Permission.EDIT_PATIENT)) {
			buttonBar.add(userButton);
		}
		if (ClientManager.SESSION.hasPermission(Permission.INVOICE)) {
			buttonBar.add(invoiceButton);
		}
		buttonBar.add(accountButton);
		buttonBar.add(search);
		buttonBar.add(searchGo);
		searchGo.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				List<User> resultsList;
				if (ClientManager.SESSION.hasPermission(Permission.ADMIN)) {
					resultsList = UserService.findUsers(search.getText());
				} else {
					resultsList = PatientService.findPatients(search.getText());
				}
				EventBus.BUS.fireEvent(new PatientSearch(resultsList));
			}
		});
	}
}
